// https://leetcode.cn/problems/partition-labels/?envType=study-plan-v2&envId=top-100-liked

// 算法思路总结：
// 1. 贪心算法划分字符串为最多片段
// 2. 预处理记录每个字符最后出现的位置
// 3. 遍历时维护当前片段的结束边界
// 4. 到达当前片段边界时记录长度并开始新片段
// 5. 时间复杂度：O(n)，空间复杂度：O(1)

#include <iostream>
using namespace std;

#include <vector>
#include <algorithm>
#include <string>

class Solution 
{
public:
    vector<int> partitionLabels(string s) 
    {
        int length = s.size();
        vector<int> ret;

        int hash[28] = {0};
        for (int i = 0 ; i < length ; i++)
        {
            hash[s[i] - 'a'] = i;
        }

        int start = 0, end = 0;
        for (int i = 0 ; i < length ; i++)
        {
            end = max(end, hash[s[i] - 'a']);
            if (end == i)
            {
                ret.push_back(end - start + 1);
                start = end + 1;
                end = end + 1;
            }
        }

        return ret;
    }
};

int main()
{
    string s1 = "ababcbacadefegdehijhklij";
    string s2 = "eccbbbbdec";

    Solution sol;

    vector<int> v1 = sol.partitionLabels(s1);
    vector<int> v2 = sol.partitionLabels(s2);

    for (const int& num : v1)
        cout << num << " ";
    cout << endl;
    
    for (const int& num : v2)
        cout << num << " ";
    cout << endl;

    return 0;
}